package com.touchstone.cloudpacs.common.aspect;

import com.touchstone.cloudpacs.common.annotation.MonitorLog;
import com.touchstone.cloudpacs.common.constant.UserConstant;
import com.touchstone.cloudpacs.common.utils.CommonUtils;
import com.touchstone.cloudpacs.entity.OperateLog;
import com.touchstone.cloudpacs.entity.User;
import com.touchstone.cloudpacs.service.IOperateLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * @Description : 操作日志切面
 * @Author : hunter
 * @Date: 2019-07-11 16:20
 **/
@Slf4j
@Aspect
@Component
public class MonitorLogAspect {

    @Autowired
    private IOperateLogService logService;
    @Autowired
    private HttpServletRequest request;

    private OperateLog operateLog;

    @Pointcut(value = "@annotation(com.touchstone.cloudpacs.common.annotation.MonitorLog)")
    public void pointCut() {
    }

    @Before(value = "pointCut() && @annotation(monitorLog)", argNames = "joinPoint, monitorLog")
    public void before(JoinPoint joinPoint, MonitorLog monitorLog) {
        operateLog = new OperateLog();
        //获取ip
        operateLog.setIpAddress(CommonUtils.getIP(request));
        //获得浏览器类型
        operateLog.setClient(CommonUtils.getBrowser(request));
        //设置操作内容
        operateLog.setContent(monitorLog.value());
        User user = (User) request.getSession().getAttribute(UserConstant.CURRENT_USER);
        //登录之后都能取到值
        if (user != null) {
            operateLog.setUserId(user.getId());
            operateLog.setUserName(user.getUserName());
        }
        //设置请求url
        operateLog.setUrl(request.getRequestURL().toString());
        //设置请求方式
        operateLog.setHttpMethod(request.getMethod());
        //设置请求方法
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        operateLog.setClassMethod(classMethod);
        //设置请求参数
        String args = Arrays.toString(joinPoint.getArgs());
        operateLog.setParameters(args);
    }

    @AfterReturning(pointcut = "pointCut()", returning = "result")
    public void doAfterReturning(Object result) {
        //设置返回结果
        operateLog.setResult(result == null ? "" : result.toString());
        User user = (User) request.getSession().getAttribute(UserConstant.CURRENT_USER);
        if (user != null && CommonUtils.isEmpty(operateLog.getUserId())) {
            //如果此刻在session里面存在用户信息，并且before里面是空的，说明是登录操作，需记录登录用户信息
            operateLog.setUserId(user.getId());
            operateLog.setUserName(user.getUserName());
            //参数设为空，避免暴露密码
            operateLog.setParameters(null);
        }
        logService.save(operateLog);
    }
}
